<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="设备编号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                                v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                                @focus="focusSel">
                                <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                            </a-select> -->
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.dropDownData" @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar style="float: right" :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler"
            @select="selectHandler" @export="exports" @import="importHandler" @excel="downloadHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
          :localeText="localeText1" @columnResized="onColumnResized" @columnMoved="onColumnMoved"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :current="pagination.page"
      :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      style="justify-content: center" />
    <a-drawer ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false" :width="400"
      popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd" :ok-loading="pageData.pageLoading"
      placement="bottom" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="min-width: 1500px; overflow: auto" class="scrollbar">
        <el-scrollbar>
          <a-tabs   :lazy-load="true">
            <a-form ref="formRef" layout="horizontal" :model="dataForm" :label-col-props="{ span: 10 }"
              :wrapper-col-props="{ span: 14 }">
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="设备编号" field="controlMachineCode"
                    :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '设备编号必填' }]">
                    <!-- <a-input class="bacClass" v-model="dataForm.controlMachineCode" /> -->
                    <a-select popup-container="html"  class="bacClass" :loading="loading3" @search="handleSearch3" @focus="focusSel3"
                      @change="handcode()" v-model="dataForm.controlMachineCode" :filter-option="false" allow-search
                      allow-clear>
                      <a-option v-for="item in pageData.MacList" :value="item['machineCode']">{{ item["machineCode"]
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="位置">
                    <a-input class="bacClass" v-model="dataForm.coordinate" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="型号">
                    <a-input class="bacClass" v-model="dataForm.model" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="自动手动">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.automanual" allow-clear>
                      <a-option>手动</a-option>
                      <a-option>自动</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>

              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="设备名称">
                    <a-input disabled v-model="dataForm.controlMachineName" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="载量(磅)">
                    <a-input-number class="bacClass" v-model="dataForm.capacityPound" :min="0" :precision="0" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="载量(KG)">
                    <a-input-number class="bacClass" v-model="dataForm.capacityKg" :min="0" :precision="0" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="设备类型">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.controlMachineType">
                      <a-option>汽液缸</a-option>
                      <a-option>水流缸</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>

              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="装机功率">
                    <a-input-number class="bacClass" v-model="dataForm.installPower" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="设备类别">
                    <a-input disabled v-model="dataForm.controlMachineCategory" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="缸型">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.vatType">
                      <a-option>E缸</a-option>
                      <a-option>S缸</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="采购公司" field="useCompanyId"
                    :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '采购公司必填' }]">
                    <a-cascader v-model="dataForm.useCompanyId" :options="pageData.firmGroupList" allow-clear ref="casOb"
                      @change="cascaderChange($event, dataForm.useCompanyId)" class="bacClass" popup-container="html"
                      :title="dataForm.useCompanyId" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="采购部门">
                    <a-cascader v-model="dataForm.useDepartment" :options="pageData.bmList" allow-clear ref="casOb1"
                      :disabled="dataForm.useCompanyId == null || dataForm.useCompanyId == ''" @change="cascaderChange1"
                      :class="{
                        bacClass: !(dataForm.useCompanyId == null || dataForm.useCompanyId == ''),
                      }" :title="dataForm.useDepartment" popup-container="html"/>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="最低水位">
                    <a-input-number class="bacClass" v-model="dataForm.lowWater" :min="0" :precision="0" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="副缸扣水">
                    <a-input-number class="bacClass" v-model="dataForm.assistantVatMinWater" :min="0" :precision="0" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="工序">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.processName" @focus="focusSel1" @search="handleSearch1"
                      :loading1="loading1" allow-clear>
                      <a-option v-for="item in pageData.ProcessNameList" :value="item">
                        {{ item }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="设备产能">
                    <a-input-number class="bacClass" v-model="dataForm.equipmentCapacity" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="副缸系数">
                    <a-input-number class="bacClass" v-model="dataForm.assistantVatCoefficient" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="副缸最高水位">
                    <a-input-number class="bacClass" v-model="dataForm.assistantVatMaxWater" :min="0" :precision="0" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="最低浴比">
                    <a-input-number class="bacClass" v-model="dataForm.minBathWater" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>

              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="最大浴比">
                    <a-input-number class="bacClass" v-model="dataForm.maxBathWater" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="管型">
                    <a-select popup-container="html"  class="bacClass" v-model="dataForm.tubeType">
                      <a-option>6</a-option>
                      <a-option>4</a-option>
                      <a-option>3</a-option>
                      <a-option>2</a-option>
                      <a-option>1</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="使用类型">
                    <a-input class="bacClass" v-model="dataForm.useType" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="理论条数">
                    <a-input class="bacClass" v-model="dataForm.theoryNum" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="对应中控代号">
                    <a-input-number class="bacClass" v-model="dataForm.controlCode" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="6">
                  <a-form-item label-col-flex="110px" label="对应中控编号">
                    <a-input-number class="bacClass" v-model="dataForm.controlNo" :min="0" :precision="2" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label-col-flex="110px" label="备注">
                    <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear
                      show-word-limit />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-tabs>
        </el-scrollbar>
      </div>
      <template #footer>
        <a-button @click="pageData.showAdd = false">关闭</a-button>
        <a-button type="primary" @click="sideOk">保存</a-button>
        <a-button type="primary" @click="copyPro">复制</a-button>
      </template>
    </a-drawer>
    <a-modal v-model:visible="pageData.visible" title="选择设备编号复制" :draggable="true">
      <a-form-item label="设备编号" style="padding-left:17%">
        <a-select popup-container="html"  class="bacClass" style="width:250px" v-model="dataForm.controlMachineId" @focus="focusSel4"
          @search="handleSearch4" @change="copyCode" :loading="loading4" :filter-option="false" allow-search>
          <a-option v-for="item in pageData.MachineList" :value="item.controlMachineName" :key="item.id">
            {{ item.controlMachineName }}
          </a-option>
        </a-select>
      </a-form-item>
      <template #footer>
        <a-button size="small" @click="pageData.visible = false">取消</a-button>
        <a-button type="primary" size="small" @click="handleSave">确认</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from '@/api/paging'
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { AnyARecord } from 'dns'

import { localeText } from '@/api/aggridZw'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

interface BrandInfo {
  id: any
  remark: string | undefined
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  deleteState: any
  obsoleteState: any
  controlMachineCode: any
  model: string | undefined
  automanual: string | undefined
  controlMachineName: string | undefined
  capacityPound: any
  capacityKg: any
  controlMachineType: string | undefined
  installPower: any
  controlMachineCategory: string | undefined
  vatType: string | undefined
  useDepartment: string | undefined
  lowWater: any
  assistantVatMinWater: any
  processName: string | undefined
  equipmentCapacity: any
  assistantVatCoefficient: any
  assistantVatMaxWater: any
  minBathWater: any
  maxBathWater: any
  tubeType: any
  useType: string | undefined
  theoryNum: string | undefined
  controlCode: any
  controlNo: any
  useCompanyName: any
  useCompanyId: any
  frimName: any
  applyBranchId: any
  useDepartmentId: any
  coordinate: any
  controlMachineId: any
}

export default {
  name: 'CentralControlMachine',
  setup() {
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }

    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)
    //查询方法
    function doRefresh() {
      pageData.pageLoading = true
      // // updateGridState01()
      post({
        url: '/pdm/controlMachine/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: '0',
          controlMachineCode: pageData.dropDownData,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            // pagination.setTotalSize(data.total);
            gridOption.value.setRowData(data.list)
            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '设备编号',
        key: 'controlMachineCode',
        dataIndex: 'controlMachineCode',
        width: 160,
      },
      {
        title: '位置',
        key: 'coordinate',
        dataIndex: 'coordinate',
        width: 160,
      },
      {
        title: '型号',
        key: 'model',
        dataIndex: 'model',
        width: 160,
      },
      {
        title: '自动手动',
        key: 'automanual',
        dataIndex: 'automanual',
        width: 160,
      },
      {
        title: '设备名称',
        key: 'controlMachineName',
        dataIndex: 'controlMachineName',
        width: 160,
      },
      {
        title: '载量(磅)',
        key: 'capacityPound',
        dataIndex: 'capacityPound',
        width: 160,
      },
      {
        title: '载量(KG)',
        key: 'capacityKg',
        dataIndex: 'capacityKg',
        width: 160,
      },
      {
        title: '设备类型',
        key: 'controlMachineType',
        dataIndex: 'controlMachineType',
        width: 160,
      },
      {
        title: '装机功率',
        key: 'installPower',
        dataIndex: 'installPower',
        width: 160,
      },
      {
        title: '设备类别',
        key: 'controlMachineCategory',
        dataIndex: 'controlMachineCategory',
        width: 160,
      },
      {
        title: '缸型',
        key: 'vatType',
        dataIndex: 'vatType',
        width: 160,
      },
      {
        title: '采购部门',
        key: 'useDepartment',
        dataIndex: 'useDepartment',
        width: 160,
      },
      {
        title: '最低水位',
        key: 'lowWater',
        dataIndex: 'lowWater',
        width: 160,
      },
      {
        title: '副缸扣水',
        key: 'assistantVatMinWater',
        dataIndex: 'assistantVatMinWater',
        width: 160,
      },
      {
        title: '工序',
        key: 'processName',
        dataIndex: 'processName',
        width: 160,
      },
      {
        title: '设备产能',
        key: 'equipmentCapacity',
        dataIndex: 'equipmentCapacity',
        width: 160,
      },
      {
        title: '副缸系数',
        key: 'assistantVatCoefficient',
        dataIndex: 'assistantVatCoefficient',
        width: 160,
      },
      {
        title: '副缸最高水位',
        key: 'assistantVatMaxWater',
        dataIndex: 'assistantVatMaxWater',
        width: 160,
      },
      {
        title: '最低浴比',
        key: 'minBathWater',
        dataIndex: 'minBathWater',
        width: 160,
      },
      {
        title: '最大浴比',
        key: 'maxBathWater',
        dataIndex: 'maxBathWater',
        width: 160,
      },
      {
        title: '管型',
        key: 'tubeType',
        dataIndex: 'tubeType',
        width: 160,
      },
      {
        title: '使用类型',
        key: 'useType',
        dataIndex: 'useType',
        width: 160,
      },
      {
        title: '理论条数',
        key: 'theoryNum',
        dataIndex: 'theoryNum',
        width: 160,
      },
      {
        title: '对应中控代号',
        key: 'controlCode',
        dataIndex: 'controlCode',
        width: 160,
      },
      {
        title: '对应中控编号',
        key: 'controlNo',
        dataIndex: 'controlNo',
        width: 160,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 160,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 160,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 200,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 160,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 200,
      },
      {
        title: '操作',
        key: 'id',
        slotName: 'act',
        width: 160,
        fixed: 'right',
      },
    ])
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 80
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 60,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 60,
        maxWidth: 60,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)

    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      ProcessNameList: []
      firmListsy: any[]
      bmListsy: any[]
      firmList: any[]
      bmList: any[]
      title: any
      title1: any
      firmGroupList: any[]
      MacList: any[]
      visible: boolean
      MachineList: any[]
    }>({
      MacList: [],
      nameList: [],
      showAdd: false,
      sideTitle: '新增中控机台表',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      ProcessNameList: [],
      firmListsy: [],
      bmListsy: [],
      firmList: [],
      bmList: [],
      title: '',
      title1: '',
      firmGroupList: [],
      visible: false,
      MachineList: [],
    })

    interface gcType {
      id: any
      company: any
    }
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ field: 'controlMachineCode', deleteState: 0 })
    }

    //下拉数据
    const options = ref<any>(pageData.nameList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { controlMachineCode: value, deleteState: 0 }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.nameList
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: '/pdm/controlMachine/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['controlMachineCode'])
          })
          pageData.nameList = dataList
        } else {
          Message.error({
            content: '查询失败！',
            duration: 6000,
          })
        }
      })
    }
    const casOb = ref()
    const casOb1 = ref()
    //公司改变
    const cascaderChange = (event: any, val: any) => {
      dataForm.applyBranchId = null
      dataForm.useDepartment = ''
      dataForm.useDepartmentId = ''
      //拿到选中的这个节点数组
      setTimeout(function () {
        if (casOb.value.selectViewValue.length != 0) {
          dataForm.useCompanyName = slicing(casOb.value.selectViewValue[0]['label'])
        }
      }, 100)
      getBmGroup(val)
    }
    //部门改变
    const cascaderChange1 = (val: any) => {
      //拿到选中的这个节点数组
      setTimeout(function () {
        if (casOb1.value.selectViewValue.length != 0) {
          dataForm.useDepartment = slicing(casOb1.value.selectViewValue[0]['label'])
          dataForm.useDepartmentId = val
        }
      }, 100)
    }
    // 获取部门列表
    const getBmGroup = (val: any) => {
      post({
        url: 'org/baCompany/getDepartmentTree?companyId=' + val,
      }).then((result) => {
        if (result.code === 200) {
          pageData.bmList = result.data
        }
      })
    }
    // 获取公司列表
    const getFirmGroup = () => {
      post({
        url: 'org/baCompany/getTreeCompanyByUser',
        data: {},
      }).then(({ code, data }) => {
        if (code === 200) {
          pageData.firmGroupList = data
        }
      })
    }
    onMounted(() => {
      getFirmGroup()
      // 切换tap到本页面执行的方法
      emitter.on('CentralControlMachine', () => {
        // selCxAll({});
        doRefresh()
      })
      pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
      //弹出层的高
      if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight
      }
      window.addEventListener('resize', () => {
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight
        }
      })
    })

    let cxbl = {}
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      controlMachineCode: '',
    })
    const addHandler = () => {
      selCxAll1({ controlMachineCode: '' })
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else if (key === 'controlMachineName' || key === 'controlMachineCategory') {
          dataForm[key] = "染色机"
        } else if (key === 'processName') {
          dataForm[key] = "染色"
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增中控机台表'
    }
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      deleteState: 0,
      obsoleteState: '',
      controlMachineCode: null,
      model: '',
      automanual: '',
      controlMachineName: '',
      capacityPound: '',
      capacityKg: '',
      controlMachineType: '',
      installPower: '',
      controlMachineCategory: '',
      vatType: '',
      useDepartment: '',
      lowWater: '',
      assistantVatMinWater: '',
      processName: '',
      equipmentCapacity: '',
      assistantVatCoefficient: '',
      assistantVatMaxWater: '',
      minBathWater: '',
      maxBathWater: '',
      tubeType: '',
      useType: '',
      theoryNum: '',
      controlCode: '',
      controlNo: '',
      useCompanyName: '',
      useCompanyId: '',
      applyBranchId: '',
      frimName: '',
      useDepartmentId: '',
      coordinate: '',
      controlMachineId: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
      colState.value = params.columnApi
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          pageData.pageLoading = true
          if (pageData.sideTitle === '新增中控机台表') {
            post({
              url: '/pdm/controlMachine/insert',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '新增成功',
                    duration: 6000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 6000,
                  })
                }
                doRefresh()
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
          } else {
            post({
              url: '/pdm/controlMachine/update',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 6000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 6000,
                  })
                }
                //doRefresh();
              })
              .finally(() => {
                doRefresh()
                pageData.pageLoading = false
              })
          }
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: '/pdm/controlMachine/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 6000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '修改失败',
                  duration: 6000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }
    const editHandler = (record: BrandInfo) => {
      // selCxAll1({ key: "" })
      //循环对象 赋值
      for (let key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改中控机台表'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值只能是英文数字组合或英文，数字！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    // const inputBlur = () => {
    //     dataForm.processName = dataForm.processName.toUpperCase();
    // }
    //导出
    const exports = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        gridOption.value.getSelectedRows().forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
          '<th>序号</th><th>中控机台表</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return (
            gridOption.value
              .getSelectedRows()
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['id'] + '</td>'
          body += '<td>' + o['controlMachineCode'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '中控机台表', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/pdm/controlMachine/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '中控机台表.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/pdm/controlMachine/importModelData', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    //下拉框得到焦点 物料编号
    const focusSel1 = () => {
      selCxAll1({ processName: '' })
    }
    //下拉数据 物料编号
    const options1 = ref<any>(pageData.ProcessNameList)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { processName: value, deleteState: 0 }
        loading1.value = true
        selCxAll1(ob)
        options1.value = pageData.ProcessNameList
        loading1.value = false
      } else {
        options1.value = []
      }
    }
    //下拉框查询 物料编号
    function selCxAll1(val: any) {
      post({
        url: '/pdm/DyeProcess/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['processName'])
          })
          pageData.ProcessNameList = dataList
        } else {
        }
      })
    }

    //   //公司改变 部门为=空
    //   const changeGs = (num: any) => {
    //             if (num == 1) {
    //                 dataForm.needDepartment = ""
    //             } else {
    //                 dataForm.useDepartment = ""
    //             }
    //         }
    //拿到所有公司
    // const foucusUseFrim = (num: any) => {
    //   let ob = {}
    //   if (num == 3) {
    //     ob['firmName'] = ''
    //     ob['department'] = ''
    //     // ob['firmTypeId'] = ""
    //   }
    //   if (num == 4) {
    //     if (dataForm.useCompanyId !== '' && dataForm.useCompanyId !== undefined) {
    //       let list = pageData.firmListsy.filter(function (o: any) {
    //         return o['id'] == dataForm.useCompanyId
    //       })
    //       ob['firmName'] = list[0]['firmName']
    //       dataForm.useCompanyName = list[0]['typeName']
    //         ? list[0]['typeName'] + '-' + list[0]['firmName']
    //         : list[0]['firmName']
    //       ob['department'] = list[0]['department']
    //       ob['firmTypeId'] = list[0]['firmTypeId']
    //     } else {
    //       Message.warning({
    //         content: '请先选择采购公司',
    //         duration: 6000,
    //       })
    //     }
    //   }
    //   // getFrimList(ob, num)
    // }
    const options2 = ref(pageData.firmList)
    const loading2 = ref(false)

    const handleSearch2 = (value: any) => {
      if (value) {
        loading2.value = true
        options2.value = pageData.firmList
        loading2.value = false
      } else {
        options2.value = []
      }
    }
    // function getFrimList(ob: any, nums: any) {
    //   post({
    //     // url: 'org/firmGroup/getFirmInfoByMap',
    //     // data: ob,
    //   }).then((result: any) => {
    //     if (result.code === 200) {
    //       if (nums == 3) {
    //         pageData.firmListsy = result.data
    //       }
    //       if (nums == 4) {
    //         pageData.bmListsy = result.data
    //       }
    //     } else {
    //       Message.error(result.message)
    //     }
    //   })
    // }
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      width: 150
    }
    const pagingList1: any = ref(pagingList)
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }

    //新增 商品号
    const focusSel3 = () => {
      selCxAll3({ "machineCode": "", deleteState: 0 });
    }
    const options3 = ref<any>(pageData.MacList);
    const loading3 = ref(false);
    const handleSearch3 = (value: any) => {
      if (value) {
        const ob = { machineCode: value, deleteState: 0 }
        loading3.value = true;
        selCxAll3(ob);
        options3.value = pageData.MacList;
        loading3.value = false;
      } else {
        options3.value = []
      }
    }
    function selCxAll3(val: any) {
      post({
        url: "/aps/dwMachine/getFieldValue",
        data: val
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.MacList = data;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }
    const handcode = () => {
      dataForm.coordinate = ''
      post({
        url: '/aps/dwMachine/getMachinePara',
        data: {
          machineCode: dataForm.controlMachineCode,
        },
      }).then((res: any) => {
        if (res.code == 200) {
          dataForm.coordinate = res.data[0].coordinate
        }
      })
    }

    //下拉框得到焦点 复制设备编号
    const focusSel4 = () => {
      selCxAll4({ "controlMachineCode": "", deleteState: 0 });
    }

    //下拉数据 复制设备编号
    const options4 = ref<any>(pageData.MachineList);
    const loading4 = ref(false);
    const handleSearch4 = (value: any) => {
      if (value) {
        const ob = { controlMachineCode: value, deleteState: 0 }
        loading4.value = true;
        selCxAll4(ob);
        options4.value = pageData.MachineList;
        loading4.value = false;
      } else {
        options4.value = []
      }
    };
    //下拉框查询 复制设备编号
    function selCxAll4(val: any) {
      post({
        url: "/pdm/controlMachine/selectControlMachineCode",
        data: val
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.MachineList = data.list;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    let controlMachine = ''
    const copyCode = () => {
      controlMachine = dataForm.controlMachineId
      dataForm.controlMachineId = dataForm.controlMachineId.split('——')[0]
    }

    //复制
    function copyPro() {
      pageData.visible = true
      dataForm.controlMachineId = ''
    }

    function handleSave() {
      let ids: any = pageData.MachineList.find((o: any) => o.controlMachineName === controlMachine)
      post({
        url: "/pdm/controlMachine/getControlMachine",
        data: {
          id: ids.id
        }
      }).then(({ data, code, message }: any) => {
        if (code === 200) {
          for (let key in dataForm) {
            if (key !== 'id' && key !== 'controlMachineCode' && key !== 'coordinate') {
              dataForm[key] = data[key];
            }
          }
          pageData.visible = false
        } else {
          Message.error({
            content: message,
            duration: 5000,
          });
        }
      });
    }

    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('CentralControlMachine01', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    return {
      copyCode,
      handleSave,
      copyPro,
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      handcode,
      pagingList1,
      huiche,
      localeText1,
      options2,
      loading2,
      handleSearch2,
      // changeGs,
      // foucusUseFrim,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      // inputBlur,
      exports,
      options,
      loading,
      cascaderChange,
      casOb,
      casOb1,
      cascaderChange1,
      getBmGroup,
      getFirmGroup,
      handleSearch,
      focusSel,
      downloadHandler,
      importHandler,
      options1,
      options3,
      options4,
      loading1,
      loading3,
      loading4,
      handleSearch1,
      handleSearch3,
      handleSearch4,
      focusSel1,
      focusSel3,
      focusSel4,
      headerShow,
      handleChange,
      PageSize,
      change1,
      defaultColDef,
      tc,
      gridOption,
      gridReady,
      total,
      page,
      size,
    }
  },
  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>